package com.example.pceb.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.pceb.entity.Course;
import com.example.pceb.entity.Enrollment;
import com.example.pceb.mapper.CourseMapper;
import com.example.pceb.mapper.EnrollmentMapper;
import com.example.pceb.service.putCourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class putCourseServiceImpl implements putCourseService {
    @Autowired private EnrollmentMapper enrollmentMapper;
    @Autowired private CourseMapper courseMapper;
    public void addCourse(Course course) {
        courseMapper.insert(course);
    }

    public Course getCourseById(Long id) {
        return courseMapper.selectById(id);
    }

    public List<Course> getAllCourses() {
        return courseMapper.selectList(null);
    }

    public void enroll(Long studentId, Long courseId) {
        System.out.println("选课 studentId = " + studentId + ", courseId = " + courseId);

        Enrollment enrollment = new Enrollment();
        enrollment.setStudentId(studentId);
        enrollment.setCourseId(courseId);
        enrollment.setEnrollTime(LocalDateTime.now());
        enrollment.setStatus("pending");
        try {
            enrollmentMapper.insert(enrollment);
            System.out.println("servece正常3");
        } catch (Exception e) {
            System.err.println("插入异常: " + e.getMessage());
            e.printStackTrace(); // 打印完整堆栈信息
            throw e; // 重新抛出异常，保持原有行为
        }
    }
    public List<Course> getCoursesByEnterpriseId(Long enterpriseId) {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("enterprise_id", enterpriseId);
        return courseMapper.selectList(queryWrapper);
    }
    public List<Course> getCoursesByStudent(Long studentId) {
        List<Enrollment> enrollments = enrollmentMapper.selectList(
                new QueryWrapper<Enrollment>().eq("student_id", studentId));
        return enrollments.stream()
                .map(e -> courseMapper.selectById(e.getCourseId()))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }
}
